import React, { useCallback, useContext } from 'react';
import { Card, Tabs, Empty, Skeleton } from 'antd';
import { router, withRouter } from 'umi';
import { formatMessage } from 'umi';
import { connect } from 'umi';

import routers from '@/../config/sub.router.config';
import styles from '@/components/PageRouter/PageRouter.less';
import helper from '@/utils/auth/helper';

import { TabStoreContext } from '@/pages/SalaryManage/constant/TabStoreContext';
import OrganizationSelect from '@/components/OrganizationSelect';

const { TabPane } = Tabs;

const handleChange = key => {
    history.push(key);
};

const Router = ({
    type,
    authCodeMap,
    children,
    countryNameCode,
    menuMap,
    activePath,
    match,
    extraButton,
    organizationResponse,
    selectOrganizationCode,
    handleOrganizationChange,
    dispatch
}) => {
    if (!countryNameCode || !organizationResponse) {
        return <Skeleton loading />;
    }

    const route = routers[type];

    // 前两个map用来处理tab路由名称和主路由名称的不同
    let routeFlag = route
        .map(item => ({ ...menuMap[item.path], ...item }))
        .map(item => {
            let { name } = item;
            if (item.editName) {
                const localeAry = item.locale.split('.');
                localeAry.splice(localeAry.length - 1, 1, item.editName);
                name = formatMessage({ id: localeAry.join('.') });
            }

            return {
                ...item,
                name
            };
        })
        .filter(item => helper.checkCode(item.code))
        .filter(item => (countryNameCode ? authCodeMap[countryNameCode]?.includes(item.code) : false));

    const hasNoMatch = routeFlag.length === 0;

    routeFlag = hasNoMatch
        ? [
              {
                  name: <>&nbsp;</>,
                  path: '#empty'
              }
          ]
        : routeFlag;

    const activeKey = routeFlag.find(item => item.path === match.path) || '';
    const content = hasNoMatch ? (
        <div style={{ paddingTop: 70, paddingBottom: 50, background: '#fff', margin: 0, position: 'relative' }}>
            <Empty description="该国别/地区暂不支持" />
            <div style={{ position: 'absolute', top: 20, right: 24 }}>
                <OrganizationSelect
                    isStrictly
                    isNeedPermission
                    style={{ width: 220 }}
                    onChange={orgCode => handleOrganizationChange(orgCode, dispatch)}
                    value={selectOrganizationCode}
                    allowClear={false}
                    dropdownMatchSelectWidth
                />
            </div>
        </div>
    ) : (
        children
    );

    if (!activeKey && !activePath) {
        if (!hasNoMatch) {
            history.push({
                pathname: routeFlag[0].path
            });
        }
        return content;
    }

    return (
        <Card bordered={false} className={styles.card} bodyStyle={{ padding: '0 16px 16px' }}>
            <Tabs
                size="large"
                className={styles.tabs}
                activeKey={activePath || activeKey.path}
                onTabClick={handleChange}
                tabBarExtraContent={extraButton}
            >
                {routeFlag ? routeFlag.map(item => <TabPane tab={item.name} key={item.path} />) : null}
            </Tabs>
            {content}
        </Card>
    );
};

const RouterConn = (namespace, authCodeMap) =>
    withRouter(
        connect(({ menu, [namespace]: model }) => {
            const { selectOrganizationCode } = model;

            const handleOrganizationChange = (value, dispatch) => {
                if (selectOrganizationCode !== value) {
                    dispatch({
                        type: `${namespace}/setMultiStore`,
                        payload: {
                            selectOrganizationCode: value,
                            countryNameCode: null
                        }
                    });
                }
            };

            return {
                menuMap: menu.breadcrumbNameMap,
                countryNameCode: model.countryNameCode,
                organizationResponse: model.organizationResponse,
                selectOrganizationCode: model.selectOrganizationCode,
                authCodeMap,
                handleOrganizationChange
            };
        })(Router)
    );

const TabContextRouter = withRouter(
    connect(({ menu }) => ({
        menuMap: menu.breadcrumbNameMap
    }))(({ authCodeMap, children, ...otherProps }) => {
        const {
            store: { countryNameCode, organizationResponse, selectOrganizationCode },
            mergeTabStore
        } = useContext(TabStoreContext);

        const handleOrganizationChange = useCallback(
            value => {
                if (selectOrganizationCode !== value) {
                    mergeTabStore({
                        selectOrganizationCode: value,
                        countryNameCode: null
                    });
                }
            },
            [mergeTabStore, selectOrganizationCode]
        );

        return (
            <Router
                {...otherProps}
                countryNameCode={countryNameCode}
                organizationResponse={organizationResponse}
                authCodeMap={authCodeMap}
                handleOrganizationChange={handleOrganizationChange}
                selectOrganizationCode={selectOrganizationCode}
            >
                {children}
            </Router>
        );
    })
);

export { RouterConn as MenuRouter, TabContextRouter as TabMenuRouter };
